package com.jiunuan.live.core.server.common;

import com.jiunuan.live.im.constants.ImConstants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-10 21:21
 * @Description: 解码器
 */

public class TcpImMsgDecoder extends ByteToMessageDecoder {
    private static final int BASE_LEN = 2+4+4; //1个short和2个int
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        // byteBuf 内容基本校验，长度校验，magic值校验
        if(byteBuf.readableBytes() >= BASE_LEN){
            if(byteBuf.readShort() != ImConstants.DEFAULT_MAGIC){
                ctx.close();
                return;
            }
            // 读取顺序取决于消息编码顺序
            int code = byteBuf.readInt(); // code
            int len = byteBuf.readInt(); // length
            // 确保byteBuf剩余的消息长度足够
            if(byteBuf.readableBytes() < len){
                ctx.close();
                return;
            }
            byte[] body = new byte[len];
            byteBuf.readBytes(body);
            // 将byteBuf转化为imMsg对象
            ImMsg imMsg = new ImMsg();
            imMsg.setCode(code);
            imMsg.setLen(len);
            imMsg.setMagic(ImConstants.DEFAULT_MAGIC);
            imMsg.setBody(body);
            out.add(imMsg);
        }
        // byteBuf 转化为ImMsg对象
    }
}
